package com.one.apartmentsystem.app.controller;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.one.apartmentsystem.app.domain.User;
import com.one.apartmentsystem.app.dto.LoginDTO;
import com.one.apartmentsystem.app.service.UserService;
import com.one.apartmentsystem.app.vo.UserVO;
import com.one.apartmentsystem.common.properties.JwtProperties;
import com.one.apartmentsystem.common.utils.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * 用户接口
 */
@RestController
@CrossOrigin
@RequestMapping("/app/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private WxMaService wxMaService;


    @Autowired
    JwtProperties jwtProperties;


    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    /**
     * 微信登录
     *
     * @param code 前端授权登录后传来的code
     * @return 授权信息结果
     */
    @ApiOperation("获取微信授权信息")
    @ApiImplicitParam(name = "code", value = "前端授权登录后传来的code", required = true, paramType = "query")
    @GetMapping(value = "/wechatSession/{code}")
    public Result wechatSession(@PathVariable String code) {
        Logger logger = LoggerFactory.getLogger("wechatSession");
        // 获取openId、unionid、session_key
        WxMaJscode2SessionResult sessionInfo = null;
        String token;
        User user;
        try {
            sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            String openid = sessionInfo.getOpenid();
            String sessionKey = sessionInfo.getSessionKey();
            String unionid = sessionInfo.getUnionid();
            user = userService.loginByWx(openid);
            HashMap<String, Object> map = new HashMap<>();
            map.put("openid", openid);
            map.put("useId", user.getUserId());
            token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), map);


        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        UserVO userVO = new UserVO();
        userVO.setUserInfo(user);
        userVO.setToken(token);
        return Result.ok(userVO);
    }

    /**
     * 发送验证码
     *
     * @param phone 用户电话号码
     * @return 操作结果
     */
    @PostMapping("/sendCode/{phone}")
    public Result sendCode(@PathVariable String phone, HttpSession session) {
        RedisUtil<Object> redisUtil = new RedisUtil<>();
        redisUtil.setRedisTemplate(redisTemplate);
        String code= (String) redisUtil.get(phone);
        if(code!=null)
        {
          //  SendMailUtil.sendMail(phone, code);
            log.info("已有验证码：" + code);
        }else
        {
            code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("无验证码：" + code);
           // SendMailUtil.sendMail(phone, code);
        }
        redisUtil.set(phone, code, 60);
        return Result.ok();
    }

    /**
     * 短信登录
     *
     * @param loginDTO 登录数据传输对象
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginDTO loginDTO ) {
        RedisUtil<Object> redisUtil = new RedisUtil<>();
        redisUtil.setRedisTemplate(redisTemplate);
        String code = (String) redisUtil.get(loginDTO.getPhone());
        String token;
        if(code.equals(loginDTO.getCode()))
        {
            User user = userService.login(loginDTO);
            HashMap<String, Object> map = new HashMap<>();
            map.put("userId", user.getUserId());
            map.put("code", loginDTO.getCode());
            token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), map);
            UserVO userVO = new UserVO();
            userVO.setUserInfo(user);
            userVO.setToken(token);
            return Result.ok(userVO);
        }
        else
        {
            return Result.error("验证码错误");
        }


    }

    /**
     * 更新用户信息
     * @param user  待更新的用户信息
     * @return 操作结果
     */
    @PutMapping("/update")
    public Result update( @RequestBody User user) {
        userService.update(user, new LambdaQueryWrapper<User>().eq(User::getUserId, user.getUserId()));
        return Result.ok();
    }

}
